<template>
  <a-modal
    v-model:visible="showComputed"
    width="888px"
    title="Reason for termination"
    wrap-class-name="primary-modal"
    ok-text="Terminate"
    :ok-button-props="{ disabled: !buttonAvailable }"
    @cancel="showComputed = false"
    @ok="handleTerminate"
  >
    <a-form ref="rejectFormRef" layout="vertical" :rules="rejectFormRules" :model="rejectForm">
      <a-row>
        <a-col :span="24">
          <a-form-item label="Reason" name="reason">
            <a-textarea v-model:value="rejectForm.reason" :auto-size="{ minRows: 4, maxRows: 4 }" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script setup>
import { computed, watch, inject, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import Client from '@/api/client'
import { OPERATION_SUCCESSFUL } from '@/constants/message.js'
const router = useRouter()
const { message } = inject('Feedback')
const props = defineProps({
  show: Boolean,
  clientId: String
})
const emits = defineEmits(['update:show'])
const showComputed = computed({
  get: () => props.show,
  set: val => emits('update:show', val)
})
// Reject
const rejectForm = reactive({
  reason: ''
})
watch(
  () => showComputed.value,
  val => {
    if (val) rejectForm.reason = ''
  }
)
const rejectFormRef = ref(null)
const rejectFormRules = {
  reason: [
    {
      required: true,
      whitespace: true,
      message: 'Please Input Reason',
      trigger: 'change'
    }
  ]
}
const buttonAvailable = ref(true)
const handleTerminate = () => {
  rejectFormRef.value.validate().then(() => {
    Client.terminateRevival(props.clientId, rejectForm.reason)
      .then(() => {
        message.success(OPERATION_SUCCESSFUL)
        setTimeout(() => {
          window.location = router.resolve({ path: `/client/${props.clientId}` }).href
          window.opener.location.reload()
        }, 0)
      })
      .finally(() => {
        showComputed.value = false
        buttonAvailable.value = true
      })
  })
}
</script>

<style scoped></style>
